Search code examples
javascriptbackbone.jsmarionettebackbone-viewsbackbone-routing

how to send input text value or data one view to another view?


could you please tell me how to send data from one view to another view .Actually I have one input field and button on my main screen .I want to send data of input text from one screen to another screen on button click .I want to send text of input field from one view to another view .I am able to move one screen to another on button click but I am not able to send input text on another screen

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

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

       moveTonext: function(){
          new Router().navigate('secondView', { trigger: true });
        },

Solution

  • In order to do that you need to instantiate your SecondView from the .moveToNext() function, and provide the necessary parameters:

    // app.js
    moveTonext: function(){
        new SecondView({ 
            model: new Backbone.Model({
                value: this.$("input").val()
            })
        });
    },
    

    You also need to update your second view to provide the model's attributes to the template:

    // second.js
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
    },
    

    And the template itself:

    // second.html
    <h1>Value from previous page: <%- value %></h1>
    

    Here's an updated Plunker sample.

    Edit

    The same can be achieved using parameterized routes:

    // router.js
    routes: {
        'secondView(/:msg)': 'secondView'
    },
    
    secondView: function(msg) {
      new SecondView({ model: new Backbone.Model({ value: msg || '' }) });
    }
    
    // app.js
    moveTonext: function() {
        new Router().navigate(
            'secondView/' + this.$('input').val(),
            { trigger: true }
        );
    },
    

    Here's a Plunker for this.