嗨,我很想在 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;
};
您能提供的任何帮助,我将不胜感激。