Connecting predefined HTML to Models and Views in Backbone

后端 未结 3 1354
走了就别回头了
走了就别回头了 2021-01-02 18:56

I\'m starting out with Backbone.js so I must say I\'m not yet very familiar with the concepts.

I have predefined HTML and I want to use Backbone to manage this. This

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 19:21

    Ok, I managed to figure it out.

    The idea is to loop through your existing HTML using jQuery, then creating instances of views and models of it using the jquery selectors and the preloaded json.

    HTML:

    Harry

    Jill

    Bob

    Javascript:

    $(function() {
    
        var PigModel = Backbone.Model.extend()
    
        var PigView = Backbone.View.extend({
            events: {
                'change input': function(e) {
                    this.model.set('name', e.currentTarget.value)
                    this.render()
                }
            },
            render: function() {
                this.$el.html(
                    '

    ' + this.model.get('name') + '

    ' + '' ) } }) var pig_data = [ {"name": "Harry"}, {"name": "Jill"}, {"name": "Bob"} ] // the magic starts here var pig_number = 0 $('.pig').each(function() { new PigView({ el: this, model: new PigModel(pig_data[pig_number]) }) }) })

    Jsfiddle: http://jsfiddle.net/tU3Mt/1/

    Like this I can serve a complete HTML page from the server, then load the desired elements into my backbone views/models and manage them from there.

    About wether this is the way backbone should be used or not: It may not be the most logical/efficient way to do this from a developer point of view. However, I think this approach has some important benefits:

    • The client get's HTML served directly and won't have to process any javascript before the page can be presented. This will become more noticable as your HTML gets bigger/more complex.
    • Search engines/web crawlers can read your page because it serves the complete HTML.

    For some people these points may not be that important, because a webapp will be fast after it has been loaded and search engines won't have to crawl it. However in some situations you might have a mix of a website and a webapp, where the page needs to load fast, be crawlable but also have a responsive interface which is complex enough to make a developer want to use something like backbone. If somebody has other ideas about this I sure like to hear them.

提交回复
热议问题