2017-02-28 41 views
2

我用角1.5和我做了一個工廠函數,它是返回一個文本對象是這樣的:如何讓模塊模式的每個功能都有保證?

return { 
    item: null, 
    get: function() { 
    return item; 
    }, 
    create: function() { 
    if (this.get()){ 
     this.remove(); 
    } 

    this.item = {}; 
    }, 
    remove: function() { 
    var item = this.get(); 
    if (item) { 
     this.item = null; 
    } 
    }, 
    add: function() { 
    if (!this.get()) { 
     this.create(); 
    } 

    this.item.newprop = 'value'; 
    } 
} 
  1. 請不要問我改到函數聲明。我想要一個擁有自己的動作(函數)和屬性的對象。

  2. 這種模式(如get裏面create等..)我沒有從任何地方複製。所以我想知道是否有名字?處理函數黑盒子是最好的方法嗎?

  3. 把Promise放在裏面的最好方法是什麼?所以每個函數都應該返回一個承諾

  4. then函數我需要使用bind ???

    待辦事項這樣的:

create: function() { 
    this.get() 
     .then(remove) 
     .then(function() { 
      this.item = {}; // BUT this === undefined!! 
     }); 
} 
+1

對於你的問題,爲什麼承諾的一部分是不是答案只是你修改每個方法來返回一個承諾?我不知道當你說「什麼是最好的方式來承諾內部」時你可能會問什麼?你讓你的異步操作返回承諾,然後你如果一個方法使用這些異步操作之一,你返回他們的承諾。 – jfriend00

+0

'''但是這個=== undefined !!' - 這是由於「this」是如何工作的 - 大量的關於SO的信息 - 一個解決方法(而不是使用綁定)是舊的'var _this = this;'' - 或者使用arrow =>函數 –

+0

get方法中的'item'是指什麼? – Bergi

回答

0

你必須使用綁定在每則回調函數:

var myModule = { 
    item: null, 
    get: function() {    
     return Promise.resolve(this.item); 
    }, 
    create: function() { 
     return this.remove().then(function() { 
      this.item = {}; 
     }.bind(this)); 
    }, 
    remove: function() { 
     return this.get().then(function(item) { 
      if (item) { 
       this.item = null; 
      } 
     }.bind(this));    
    }, 
    add: function() { 
     return this.get().then(function(item) { 
      return item || this.create(); 
     }.bind(this)).then(function() { 
      this.item.newprop = 'value'; 
     }.bind(this)); 
    } 
}     
// Let see it working: 
myModule.create().then(function() { 
    return myModule.get(); 
}).then(function(item) { 
    console.log("After create: ", item); 
    return myModule.remove(); 
}).then(function() { 
    return myModule.get(); 
}).then(function(item) { 
    console.log("After remove: ", item); 
    return myModule.add(); 
}).then(function() { 
    return myModule.get(); 
}).then(function(item) { 
    console.log("After add: ", item); 
});