Reputation: 9167
I'm wondering if I'm going down the correct route for doing this by using the MVVM pattern and Knockout JS, this is my current scenario:
ASCX:
<asp:TextBox runat="server" ID="TextboxDescription" Width="300" ClientIDMode="Static" />
JS:
$('#TextboxDescription').limitCharacters({
limit: 1000,
alertClass: 'error',
id_result: 'description_limit',
align: 'right'
});
So you see, I have to rely on the textbox always being called "TextboxDescription", which is where I think MVVM comes in. I'd change my code to look something like this:
ASCX:
<asp:TextBox runat="server" ID="TextboxDescription" Width="300" ClientIDMode="Static" data-bind="{ not even sure what goes here, no Knockout load event? }" />
JS:
function ViewModel() {
setLimit = function(limit, alert, id, align) {
// code here to call limitCharacters on sender(?!)
}
};
ko.applyBindings(new ViewModel());
I've been reading about custom binding in Knockout, is that a route I'm going to have to go down for this to bind with my own widgets?
Upvotes: 2
Views: 676
Reputation: 15984
You are on the right track. Here is a basic example custom binding that should do what you want (untested).
ko.bindingHandlers.limitCharacters = {
init: function(element, valueAccessor) {
// this gets called at the start when the element is first bound
// use it to bind event handlers widgets etc
var $element = $(element),
limit = ko.utils.unwrapObservable(valueAccessor()); // this gets the value of the object on the rhs of the binding
$element.limitCharacters({
limit: limit,
alertClass: 'error',
id_result: 'description_limit',
align: 'right'
});
}
}
Your binding would now look like
<asp:TextBox runat="server" ID="TextboxDescription" Width="300" ClientIDMode="Static" data-bind="limitCharacters: 1000" />
At the moment the limit could be an observable instead of simply 1000 (note the unwrapObservable call). If you would like the binding to react to the value in the observable changing then you can add an update function to the binding which gets called when a change occurs to the observable that's bound to. Here you could reinitialize your plugin or adjust it's settings.
Hope this helps,
Upvotes: 2