Jump to content

Recommended Posts

Posted

oias pips,

Vejam lá este exemplo de MVC baseado no prototypejs... fiz isto para organizar melhor o código no lado do cliente quando o javascript é enorme...

Já outros MVC javascript... gosto disto porque é simples embora falte a parte de error handling que voces podiam sugerir 👍

Digam o que se podia melhorar...

Exemplo...

Model.js:

var Model = Class.create({

initialize: function() {
	this.url	= 'service.php';
	this.parameters = {};
	this.method	= 'POST';
	this.headers	= { Accept: 'application/json' },
	this.transport	= {};
	this.format	= 'json';
},

call: function(cb) {
	new Ajax.Request(this.url,
		{
			method: this.method,
			requestHeaders: this.headers,
			parameters: this.parameters,
			onComplete: function(transport) {
				this.transport = transport;
				data = transport.responseJSON;
				if (this.format == 'text') data = transport.responseText;
				else if (this.format == 'xml') data = transport.responseXML;
				cb(data);
			},
			onFailure: function() {
				this.failure();
			}
		}
	);
},


failure: function() {
	alert('Failed!');
},

json: function() {
	return this.transport.responseJSON;
},

text: function() {
	return this.transport.responseText;
}

});

User.js

var User = Class.create(Model, {
initialize: function() {
	this.url	= 'service.php';
	this.parameters = {m: 'User'};
	this.method	= 'POST';
	this.headers	= { Accept: 'application/json' },
	this.transport	= {};
	this.format	= 'json';
},

readAll: function(cb) {
	this.parameters.f = 'all';
	this.call(cb);
},

readOne: function(id, cb) {
	this.parameters.f = 'one';
	this.parameters.id = id;
	this.call(cb);
}
});

Para as Views...

var ListView = Class.create({

initialize: function(elem, list) {
	this.elem = elem;
	this.list = list;
},

show: function() {
	var ul = new Element('ul');
	this.list.each(function(item) {
		ul.insert(new Element('li').insert(item.html));
	});
	$(this.elem).replace(ul);
}
});

var UserListView = Class.create(ListView, {

initialize: function(elem, list) {

	data = [];
	list.each(function(item) {
		item.html = item.name;
		data.push(item);
	});

	this.elem = elem;
	this.list = data;
}
});

e por fim um controlador...

var UserModel = new User();
UserModel.readAll(function(list) {
	this.UserView = new UserListView('app', list);
	this.UserView.show();
});

Podem ver um exemplo a funcionar aqui:

http://dl.dropbox.com/u/17607469/mvcjs.zip

Digam coisas... 😁

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.