I am using backbone.js to create a single page app. I am new to backbone, so please forgive any wrong semantics.

My Problem is when rendering the views.

Initially, I have a javascript in my index.html that executes the some dom manipulation(image slider).

The JS is wrapped in $(window).load() so all is fine on initiation. The code obviously doesn't execute unless the page is loaded from url. the code will not run from backbone views or router. So the page loads without the dom manipulation.

I have tried to insert my code into the render and initialize function in the view, but to no avail. Should I add this code to the router? that seems to be a bit of a hack.

Where should I include the "dom ready" code? and / or is there a better way to manage views and their dom elements on load in backbone?

the code:

home.js

window.HomeView = Backbone.View.extend({
initialize:function () {
    this.render();
},

render:function () {
    $(this.el).html(this.template());

    this.startOrbits();
    return this;
},



startOrbits:function(){
    $(window).load(function() {
        $('#orbit-main').orbit({ fluid: '16x6', swipe:true });
        $('#orbit-news').orbit({ fluid: '8x6', bullets: true, directionalNav:false, captions:true, advanceSpeed: 9000});
    });
},




});
有帮助吗?

解决方案

I was able to find a solution. After commenting out the if statement in my router function, things went smoothly.

 home: function () {
            // if (!this.homeView) {
                this.homeView = new HomeView();
            // }
            $('#main-content').html(this.homeView.el);
            this.homeView.startOrbits();
            this.headerView.selectMenuItem('home');
        },

I do realize that this means I create a new view on every rout trigger. Please feel free to offer more optimal solutions.

其他提示

But when I go to another view, then back, the code obviously doesn't excite

I'm not quite sure what that means. Leaving the "excite" part aside, you don't "go to" views; views are just ways of adding elements to the page, or adding logic to existing elements.

If I had to guess though, I'd imagine that you're using the Backbone router to move between virtual "pages" (and you use views to make those pages). If that's the case, you need to look at the Backbone router events:

http://documentcloud.github.com/backbone/#Router

http://documentcloud.github.com/backbone/#FAQ-events

Specifically, I think you want to bind an event handler (on your router) to "route:nameOfYourRoute", or just :route" (if you want to trigger your logic on every virtual page load).

Hope that helps, and if my guesses are wrong please edit your question to clarify.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top