Search code examples
javascriptjquerybackbone.jsrequirejsbackbone-views

why <h1> tag is not display using backbone?


I am trying to load one html file using backbone js and require js file .I am able to call initialise function of view but not able to load that html file here is my code

define([
    'jquery',
    'underscore',
    'backbone',

    'text!templates/stats.html'
], function ($, _, Backbone, statsTemplate) {
    'use strict';
    var AppView = Backbone.View.extend({

        // Instead of generating a new element, bind to the existing skeleton of
        // the App already present in the HTML.
        el: '#todoapp',

        // Compile our stats template
        template: _.template(statsTemplate),

        // Delegated events for creating new items, and clearing completed ones.
        events: {

        },

        // At initialization we bind to the relevant events on the `Todos`
        // collection, when items are added or changed. Kick things off by
        // loading any preexisting todos that might be saved in *localStorage*.
        initialize: function () {


   alert('-in--')
        },

        // Re-rendering the App just means refreshing the statistics -- the rest
        // of the app doesn't change.
        render: function () {

        }
        // Add a single todo item to the list by creating a view for it, and
        // appending its element to the `<ul>`.



    });

    return AppView;

})

I am getting the alert in initialize function not able to load the html file

here is my code http://plnkr.co/edit/rhoE1H9A8nfu6II64aEo?p=preview


Solution

  • Thanks for taking the time to set up a working example.

    Unfortunately Backbone doesn't give you much for free, so there are a number of manual steps to get this working:

    1. Add a <div id="todoapp"></div> to index.html as you are targeting it with el: '#todoapp' but it doesn't exist.

    2. Doing template: _.template(statsTemplate) will return a compiled version of the template (as a function). You then need to call it like a function, optionally passing in a context so that the template can render dynamic data. e.g. this.template().

    3. The render method won't get called automatically, so when you are ready to render the view (usually instantly but it could be after an AJAX response) you need to call this.render(). In your case straight away in initialize.

    4. Finally in render you can attach the rendered template to the view's element: this.$el.html(this.template());

    Updated example: http://plnkr.co/edit/6HyOhuQ7LGL91rS8slJX?p=preview

    I recommend you create a BaseView with this common render flow so you don't have to repeat it every time. Also it's a good idea in that BaseView to set up a concept of sub views which clean up properly when the parent's remove is called, and re-render when a parent's render is called.

    Here is an example of using a BaseView: http://jsfiddle.net/ferahl/xqxcozff/1/