How to pass value from one view model to another viewmodel in knockout js?

前端 未结 3 980
不思量自难忘°
不思量自难忘° 2021-01-22 00:51

i have two view models and i want to pass value from one view model to another viewmodel. i have two viewmodels and two div i want to display another div on click of button whic

3条回答
  •  难免孤独
    2021-01-22 01:24

    rjdmello already pointed you to AmplifyJS. Amplify offers (amongst other things) a publish/subscribe mechanism. Pub/sub is a good way to facilitate communication between modules that are loosely coupled. One module subscribes to a topic, and any other module can publish a message with that topic (and any data you'd like to send along). Once a topic is published, all subscribers will be notified.

    Some code demonstrating Amplify in this case:

    Container1ViewModel.prototype.showDiv = function (event) {
        amplify.publish('show-div', { clickedButton: event.target });
    }
    
    function Container2ViewModel() {
        var onShowDiv = function (data) {
            if ($(data.clickedButton).hasClass('.enabled')) {
                // Show me teh div!!
                this.myItems.push("ABC");
            }
        };
        this.myItems = ko.observableArray();
        this.myItems.push("XYZ");
        this.myItems.push("PQR");
    
        amplify.subscribe('show-div', this, onShowDiv, 1);
    }
    

    Using pub/sub to keep modules loosely coupled is generally very good practise (although you shouldn't overdo it because it will become harder to track how modules cooperate).

    And while we are on the practise of good practise, don't use self = this, use Function.prototype.bind instead. http://www.smashingmagazine.com/2014/01/23/understanding-javascript-function-prototype-bind/

提交回复
热议问题