I am new to Backbone.js. I have created a View for a button that already exists on the page. I apply jquery-ui to the button when the view is initialized:
var ButtonView = Backbone.View.extend({
el: $('#ButtonId'),
initialize: function () {
$(this.el.selector).button();
}
});
This method works, but I am wondering if there a simpler selector I could use rather than $(this.el.selector)? At first I thought I would be able to just do el.button(); but that does not work.
Or is there a better/simpler way to approach the whole process?
i can assure you
el.button();worksbut…
you need to keep in mind when your view jquery selector is executed.
when you type it like you did, your jQuery selector is executed when the view code is parsed,
meaning, this mostly happens when your dom was not ready loading.
you can best pass the
elin later like this:now, your view is instantiated on document ready, the button element is passed because the dom was ready and your selector resolves to the button element. and you can happily use
el.button();to apply something on it.example: http://jsfiddle.net/saelfaer/KEQQB/
edit
another way to do it is to define your elementselector as the el argument, and only execute it like you did.
this will work as well, but you would only be able to use this view on your given button unless you override it, the first example is cleaner for reusing code, you could instantiate it 3 times and each of them you could pass another button to…
example: http://jsfiddle.net/saelfaer/KEQQB/6/
sidenote
on a sidenote i’d suggest using the render method, you are free to do this in the init, but i believe the render method is the one that should be handling this.