开发者

Backbone.js Double Rendering Issue

I'm using Backbone.js to create an app. However it is rendering the code twice. It is as though the code is being run twice. I've looked for duplicate code and can't find anything that would run everything twice.

An example of what happens is on init the body content is supposed to be wrapped by a div#app_container tag. But when I load the page it wraps in a div#app_container then wraps that in a dev#app_container tag.

Also, if i put alert('test') in the 'initialize()' function it alerts "test" twice.

Does that make sense?

-- EDIT --

After playing around with code I've found that if I remove the line which wraps everything in the body then the problem stops. So there is something in wrapInner or affecting the body that is causing the code to be run twice.

Problem code:

$("body").wrapInner('<div id="app_container" />');

Here is the code for my app JS file:

(function ($) {

  window.AppView = Backbone.View.extend({

    self: this,

    el: $("body"),

    defaults: {
        current_selected: "",
        last_selected: "",
        toggle: 0,
        Messages: "", 
        latest_template: "",
    },

    events: {
        "click #annotate_app_container" : "select"
    },

    initialize: function()
    {
        $("body").wrapInner('<div id="app_container" />');
        $.get('/assets/includes/ajax.php', function(data){
            $("#app_container").after(data);
        });
    },

    select: function (e) {

        e.preventDefault();

        // Code goes here
    },

  });

window.App = new AppView;

})(jQuery);

This files I am including on the page are as follows:

    <script type="text/javascript" src="/assets/js/json2.js"></script>
    <script type="text/javascript" src="/assets/js/jquery.min.js"></script>
    <script type="text/javascript" src="/assets/js/underscore.js"></script>开发者_如何学C
    <script type="text/javascript" src="/assets/js/backbone.js"></script>
    <script type="text/javascript" src="/assets/js/mustache.js"></script>
    <script type="text/javascript" src="/assets/js/app.js"></script>

Let me know what you think it is.


You might check for any hash change events causing the page to load again. I had a similar behaviour once caused by an element <a href='#'> that also had an event binded to it.


It is because you do an ajax call within the document ready. It will trigger a second document ready event. You might want to do something like

setTimeout(function(){window.App = new AppView()}, 1);

Might not be the problem, but I am sure it is related to that get call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜