Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply jquery-ui to a Backbone.js view?

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?

like image 847
xcer Avatar asked Dec 09 '11 00:12

xcer


1 Answers

i can assure you el.button(); works but...

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 el in later like this:

var ButtonView = Backbone.View.extend({
    initialize: function () {
        this.el.button();
    }
});

$(function(){
    var myButton = new ButtonView({ el: $('#ButtonId') });
});

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.

var ButtonView = Backbone.View.extend({
    el: '#ButtonId'
    initialize: function () {
        $(this.el).button();
    }
});

$(function(){
    var myButton = new ButtonView({ });
});

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.

var ButtonView = Backbone.View.extend({

    initialize: function () {
        _.bindAll(this, "render");
    },

    render: function () {
        this.el.button();
        return this;
    }
});

$(function(){
    var myButton = new ButtonView({ el: $('#ButtonId') }).render();
});
like image 143
Sander Avatar answered Sep 21 '22 09:09

Sander