// include actor code first
YUI.add("actor", function(Y) {
Y.log("actor code added!");
Y.ActorModel = Y.Base.create("actorModel", Y.Model, [], {
//prototype methods - avail to all instances
showPos: function() {
Y.log("pos: left=" + this.get('left') + " top=" + this.get('top'));
},
setPos: function(obj) {
this.set("top", obj.top);
this.set("left", obj.left);
}
}, {
ATTRS: {
// Add custom model attributes here. These attributes will contain your
// model's data. See the docs for Y.Attribute to learn more about defining
// attributes.
top: {
value: 0
},
left: {
value: 0
}
}
});
Y.ActorView = Y.Base.create("actorView", Y.View, [], {
template: "<div class='actor' style='position:absolute; top: {top}px; left:{left}px'></div>",
initializer: function() {
var model = this.get('model');
// Re-render this view when the model changes, and destroy this view when
// the model is destroyed.
model.after('change', this.render, this);
model.after('destroy', this.destroy, this);
},
render: function() {
var container = this.get('container'),
html = Y.Lang.sub(this.template, this.get('model').toJSON());
// Render this view's HTML into the container element.
container.setContent(html);
// Append the container element to the DOM if it's not on the page already.
if (!container.inDoc()) {
Y.one('body').append(container);
}
return this;
}
}, {
ATTRS: {
container: {
valueFn: function() {
return Y.one("#game");
}
}
}
});
}, '1.0', {
requires: ["model"]
});
// now the "main" code
YUI().use("node", "app", "actor", function(Y) {
Y.log("yui loaded successfully.");
var myActor = new Y.ActorModel({top: 30, left: 40});
myActor.on("change", function(e){
Y.log("actorchanged!");
Y.log('change fired: ' + Y.Object.keys(e.changed).join(', '));
Y.log(e.changed);
this.showPos();
});
myActor.showPos();
myActor.setPos({left: 100, top: 100});
var myActorView = new Y.ActorView({model: myActor});
myActorView.render();
Y.on("domready", function(){
Y.log("domready");
var theArea = Y.one("#game");
theArea.on("click", function(e){
Y.log("clicked");
Y.log(e);
myActor.setPos({
left: e.clientX,
top: e.clientY
});
});
});
})
Following resources are loaded into result:
- yui-min.js
<!--
uses YUI Y.app framework. Clicking the box updates the model data, which in turn triggers an update in the view to position the box where the click event happened.
-->
<h1>YUI Y.App demo. Click anywhere in the black box to move the green box.</h1>
<div id="game"></div>
body {
background-color: slategrey;
padding: 4px;
}
#game {
border: 1px solid black;
height: 400px;
width: 400px;
}
.actor {
border: 1px solid green;
height: 30px;
width: 30px;
}