Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Overwriting Model Create Function

$
0
0
When a new model is saved, the response from the server is appended to the model instance and the .save() is resolved with the updated instance.

Is there a way to have .save() calls be resolved with a different object that has a property that is the model instance?

Here's why I ask.

My server will respond with some properties that I don't want appended to the model instance. One such field is a status message from the server. "This operation was a success." type things. There may be a few others. 

In order to create a new instance of my Player model, the server requires a few fields. Let's say name, age, position and team for sh!ts and giggles. On the backend there is ultimately a function like so:

newPlayer(name, age, position, team)

This is all the server needs or cares about in order to create a new Player. On the frontend I can easily create a Player object containing those fields and call save like so:
  1. new Player({
    name: 'Ryan Braun',
    age: 28,
    position: 'OF',
    team: 'Brewers'
    }).save()

But a Player model object is actually a lot more complex than this simple object. If you do a findAll or findOne, the response will look something like this:
  1. {
    id: 1,
    details: {
    name: 'Ryan Braun',
    age: 28
    },
    positions: [
    {
    position: 'OF'
    }
    ],
    team: {
    name: 'Brewers',
    location: 'Milwaukee',
    league: 'NL'.,
    division: 'Central'
    }
    }

What I really want to be able to do easily is call .save() and get a custom object that contains the expanded version of the Player which the server would send back along with, but separated from, any other non-model instance related fields.
  1. {
    player: { PLAYER MODEL JSON },
    status: 'The creation was a success',
    error: false
    }

Is this doable using save and/or create or do I have to write my own custom static function?

I want to make sure that the "created" event for Player models is triggered too.

Viewing all articles
Browse latest Browse all 3491

Latest Images

Trending Articles



Latest Images