Adding WinJS EventMixin to a Type

WinJS.Utilities.eventMixin is basically meant for objects that don’t have associated UI elements (it can’t use the listener methods on the element in the DOM, so it has its own implementation of these methods). We can add WinJS.Utilities.eventMixin to any type we define. It contains WinJS.Utilities.eventMixin.addEventListener, WinJS.Utilities.eventMixin.removeEventListener and WinJS.Utilities.eventMixin.dispatchEvent functions that help us to raise and handle custom events that we define on the type.

For example, the following code shows how to define a type TestType with a rename event that is raised whenever the property ‘name’ is changed. In this code, we will first mix the TestType type with WinJS.Utilities.eventMixin to get the event listener functionality and then mix it with the JS.Utilities.createEventProperties function to define the event.
When we define the name property, we use the WinJS.Utilities.eventMixin.dispatchEvent function in the setter to raise the rename event.

default.js

            var TestType = WinJS.Class.define(function (thisName)
 {   
              this.name = thisName;
                     },      
        {     
             _nameValue: "",
                 name: {
                     get: function () {  
                        return this._nameValue;
                     },
                     set: function (val) {
                         this._nameValue = val;
 // dispatchEvent function in the setter to raise the rename event.
                         this.dispatchEvent("rename");    
                  }      
            }             
 });
            WinJS.Class.mix(TestType, WinJS.Utilities.eventMixin);
     //create all the stuff a class needs to support named events.
    WinJS.Class.mix(TestType, WinJS.Utilities.createEventProperties("rename"));
            //Instantiate the object using the class name   
          var testObject = new TestType("Allen");
            //Add an event listener that writes to the mixinDiv
.             testObject.addEventListener("rename", function (evt) {
  document.getElementById("mixinDiv").innerText = "Rename event fired";
            });
            //Rename the object.  
           testObject.name = "Bob";

When we run this code the innerText value of the mixinDiv is “Rename event fired”.
NB:-You must mix the WinJS.Utilities.eventMixin with the type before you use WinJS.Utilities.createEventProperties
To test the code you can simply put the break points and watch the flow of the cursor. So mixins, are a way to add pre-canned functionality to a class, and is a convenient way to modularive code that we can use in multiple classes. It’s also good to know that we can call WinJS.Class.mix multiple times with additional mixins, and the results simply accumulate (if there are duplicates, the last member mixed is the one retained).

150 150 Burnignorance | Where Minds Meet And Sparks Fly!