嗨,我是tyring實現在JavaScript觀察者模式:如何在javascript中實現觀察者模式?
我index.js:
$(document).ready(function() {
var ironMan = new Movie();
ironMan.setTitle('IronMan');
ironMan.setRating('R');
ironMan.setId(1);
// ironMan.setCast(['Robert Downey Jr.', 'Jeff Bridges', 'Gwyneth Paltrow']);
var terminator = new Movie();
terminator.setTitle('Terminator');
terminator.setRating('P');
terminator.setId(2);
console.log(ironMan.toString());
console.log(terminator.toString());
ironMan.play();
ironMan.stop();
ironMan.download();
ironMan.share('V. Rivas');
console.log(ironMan.getCast()[0]);
});
我的電影:
var title;
var rating;
var id;
var observers;
function Movie() {
observers = new ObserverList();
}
//function Movie (title, rating, id){
// this. title = title;
// this.rating = rating;
// this.id =id;
// observers = new ObserverList();
//}
Movie.prototype.setTitle = function (newTitle) {
this.title = newTitle;
}
Movie.prototype.getTilte = function() {
return this.title;
}
Movie.prototype.setRating = function (newRating) {
this.rating = newRating;
}
Movie.prototype.getRating = function() {
return this.rating;
}
Movie.prototype.setId = function (newId) {
this.id = newId;
}
Movie.prototype.getId = function() {
return this.id;
}
Movie.prototype.play = function() {
for (i = 0; i < observers.Count; i++) {
console.log("palying...");
}
}
Movie.prototype.stop = function() {
for (i = 0; i < observers.Count; i++) {
console.log("stoped");
}
}
Movie.prototype.AddObserver = function (observer) {
observers.Add(observer);
};
最後觀察者:
function ObserverList() {
this.observerList = [];
}
ObserverList.prototype.Add = function (obj) {
return this.observerList.push(obj);
};
ObserverList.prototype.Empty = function() {
this.observerList = [];
};
ObserverList.prototype.Count = function() {
return this.observerList.length;
};
ObserverList.prototype.Get = function (index) {
if (index > -1 && index < this.observerList.length) {
return this.observerList[index];
}
};
ObserverList.prototype.Insert = function (obj, index) {
var pointer = -1;
if (index === 0) {
this.observerList.unshift(obj);
pointer = index;
} else if (index === this.observerList.length) {
this.observerList.push(obj);
pointer = index;
}
return pointer;
};
你可以提供的任何幫助,我將非常感激。
我會檢查出來,但如果我想讓它保持原樣,我該怎麼辦? –
更新了答案 –
嗨,謝謝德米特里,我應該在哪裏添加?我應該使用哪一個?在觀察員班或電影班中的人?非常感謝你 –