Skip to content

Instantly share code, notes, and snippets.

@jupiterjs
Created March 17, 2011 01:49
Show Gist options
  • Save jupiterjs/873712 to your computer and use it in GitHub Desktop.
Save jupiterjs/873712 to your computer and use it in GitHub Desktop.
How a JMVC Model that uses deferreds could / should look.
// The GOAL =========================
// 1. define a model
$.Model("Todo",{
findOne : function(params, success, error){
//some deferred gets returned here
}
},{
helperMethod : function(){ ... }
})
// 2. Use deferreds and get back model instances.
var todoDeferred = Todo.findOne({}, function(todo){
todo.helperMethod()
});
todoDeferred.then(function(todo){
todo.helperMethod()
});
/**
* How this looks now, w/o deferreds ===================
*/
findOne : function(params, success, error){
$.ajax({
url : "/todo/"+params.id,
success : this.callback(['wrap',success]) // wrap is inherited from JMVC's model, sudo code for it below
})
},
wrap : function(data){
return new this(data);
}
/**
* How this might work with converter and deferreds
*/
findOne : function(params, success, error){
$.ajax({
url : "/todo/"+params.id,
converter : this.wrap
}).then(success).error(error)
},
/**
* How this needs to be done with converters
*/
findOne : function(params, success, error){
$.ajax({
url : "/todo/"+params.id,
converters : {"json model" : this.wrap },
dataType : "json model"
}).then(success).error(error)
},
/**
* consider what if the attributes are in something like {todo : {name: 'title'}}
*/
findOne : function(params, success, error){
$.ajax({
url : "/todo/"+params.id,
converters : {"* model" : this.wrap, "* todo" : function(data){ return data.todo }},
dataType : "json todo model"
}).then(success).error(error)
},
@jupiterjs
Copy link
Author

findOne : "GET /todo/{id} .todo"

@thecountofzero
Copy link

I like it. I need to review converters and their syntax, but it's pretty clean.

I think you need a return statement before $.ajax so you can return the promise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment