简体   繁体   中英

How do I access a variable from a different view?

How do I access a variable from a different view?

I want to access selectedColor in another view:

    'onClickColor': function(e) {

        var view = this,
            selectedColor = $(e.currentTarget).data('color'), //$(this).data('color');
            style = $('<style>.highlight { color: ' + selectedColor +'; margin-left: 4px;}</style>');

        $('.initial').css('color', selectedColor);
        $('.highlight').css('color', selectedColor);
        $('html > head').append(style);
        //view.canvasColorPick(e);
    },

And then in another view, I want to pass the variable selectedColor using ajax on a form submission.

     'formCollect' : function (e) { 

        var view = this;
        var fname = $('#your_name').val();
        var email = $('#email').val();
        var state = $('#state').val();
        var color = selectedColor;
        var url = 'services/users/add?name='+fname+'&email='+email+'&state='+state+'&color='+color+'';
        $.get(url);
    },

It should be the best way – to subscribe one view to events of another one. Since you did not provide the scope your views was instantiated I assume both of them are in the global scope. If you don't understand what scope mean please read this: What is the scope of variables in JavaScript?

So assume your first view instantiated like this: firstView = new FirstView(); . The second one is secondView = new SecondView(); .

When the color changed in firstView trigger an event: this.trigger( "Color changed", {newColor: "black"} ); . Please make sure that both views was instantiated before this event triggered.

Now you need to subscribe secondView on the event of firstView: secondView.listenTo( firstView, "Color changed", secondView.handleColorChanged );

Here handleColorChanged is the event handler which will get event params as arguments.

Now alltogeather:

var FirstView = Backbone.view.extend({
  /** your casual code here */
  'onClickColor': function(e) {
     /** your code here */
     this.trigger( "Color changed", { newColor: "black" });
  }
});

var SecondView = Backbone.view.extend({
  /** your casual code here */
  'handleColorChanged': function( eventData ) {
     console.log( eventData );
  }
});

var firstView = new FirstView(),
    secnodView = new SecondView();
secondView.listenTo( firstView, "Color changed", secondView.handleColorChanged );

This is not the only one way to solve your task. But this is the way to separate views from each other. No one view knows about another one what is mostly needed in big applications, makes easy debugging process and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM