Chia Yu Pai

Front-End, HTML5, Javascript, CSS3

Posts match “ AngularJS ” tag:

Javascript Getter / Setter

| Comments

Modern browsers' (IE9 up, IE8 only on DOM Object) Javascript Engine supported Getter / Setter for Object

IE6-8 could listen onpropertychange event

我們有兩個常見的方法去實作,例子如下:

Sample A:
透過 __defineSetter____defineGetter__ 預設方法榜定

Dog = function (name) {
    this.name = name || 'Doggy';
  
  // Define setter with __defineSetter__ method.

  this.__defineSetter__("name", function(newVal){
    this.bark('My new name is ' + newVal);
  });
}

Dog.prototype.bark = function (msg){
    msg = msg || "I'm " + this.name;
    alert('Bark! ' + msg);
}

Carl = new Dog();
Carl.name = Carl // Alert: Bark! My new name is Carl

Carl.name // Carl

Sample B:
直接使用 setget 關鍵字定義

Dog = function (name) {
    this._name = name || 'Doggy'; // Default name without alert.

}

Dog.prototype = {
    bark: function (msg) {
    msg = msg || "I'm " + this.name;
        alert('Bark! ' + msg);
  },
  // Define Setter

  set name(newVal) {
    this._name = newVal;
        this.bark('My new name is ' + newVal);
  },
  // Define Getter

  get name() {
    return this._name;
  }
}

Carl = new Dog();
Carl.name = Carl // Alert: Bark! My new name is Carl

Carl.name // Carl

透過 Setter / Getter 的設定可以輕鬆的監聽物件方法的改變,目前最常用到的非屬 two-way binding 的專案。可以直接用十分抽象的方法讓使用者改變 Javascript 中物件的屬性值來換取 DOM 的直接內容變化,達到驚人的易用水準。

Frameworks:

Angular Service Event

| Comments

AngularJS 的 Event 模組只能在 controller 中使用
當需要跨越不同的 controller scope 使用時
就無法直接使用內建的 $on, $emit 來實作 Event model
有兩種(或更多)解法來完成這樣的跨 controller 需求

Service variable and $scope.$watch

controller 的 $watch 可以監控 Service 的值
透過 injector service 便可做到不同 controller 之間的訊息溝通

angular.module('testApp')
  .controller('TestCtrl', function ($scope, Watcher) {
    $scope.$watch(function(){
      return Watcher.status;
    }, function (newStatus) {
        if (newStatus === 'done') {
        // ...do something

      }
    });
    // Remember:

    // if you want listen values in object, you have to add third parameter with true.

  )
  .controller('TestCtrl2', function ($scope, Watcher) {
    // ...some async code

    var callback = function () {
        Watcher.status = 'done';
    }
  )
  .service('Watcher', function () {
    this.status = null;
  
    return this;
  });
}

Service Scope

直接建立一個 Scope 來支援內建的 Event model
轉發他的 $on, $emit 來給其他 controller 使用

angular.module('testApp')
  .controller('TestCtrl', function ($scope, Watcher) {
    Watcher.$on('fetched', function () {
        // ...do something

    });
    
    // ...some async code

    var callback = function () {
        Watcher.$emit('fetched');
    }
  )
  .service('Watcher', function ($rootScope) {
    _scope = $rootScope.$new();
    
    this.$on = _scope.$on;
    this.$emit = _scope.$emit;
  
    return this;
  });