Search code examples
javascriptbackbone.jsbackbone-viewsbackbone-routing

how to move one view to another view?


could you please tell me how to navigate from one page to another page in backbone . I want to show second html on button click how it is possible

I so like that .I resister event like that

events: {
         'click #click':'moveTonext'
        },

       moveTonext: function(){
          alert('---')
        },

I make second page like that

define([
    'jquery',
    'underscore',
    'backbone',
    'text!templates/second.html'
], function ($, _, Backbone, statsTemplate) {
    'use strict';

    var secondView = 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 () {
          this.render();
        },

        serialize: function () {
          return {
            message: 'world'
          };
        },

        // Re-rendering the App just means refreshing the statistics -- the rest
        // of the app doesn't change.
        render: function () {
          this.$el.html(this.template());
        }
        // Add a single todo item to the list by creating a view for it, and
        // appending its element to the `<ul>`.



    });

    return secondView;

})

Second html

<h1>second</h1>

here is my plunker http://plnkr.co/edit/fCXwSrroJP1l6BppjpmD?p=preview


Solution

  • Basically your button should trigger navigation, so the click handler should look like this:

    moveToNext: function () {
        router.navigate("other/path", { trigger: true });
    }
    

    Then, in your router code you need to add a route handler for the above path:

    routes: {
        "other/path": "handleOtherPath"
    },
    
    handleOtherPath: function () {
        new SecondView();
    }
    

    This is for the case when SecondView should replace FirstView. If it should be appended instead, the following mechanism can be used:

    moveToNext: function () {
        new SecondView({ el: this.$(secondViewContainerSelector) });
    }
    

    Here's a working Plunker sample.