is passing ractive as an argument good practice?

122 views Asked by At

Let's say, instead of packing your onInit and onRender sections of your Ractive declaration in your index.html with a lot of functions that need access to the Ractive object, you wish to keep the index.html cleaner and simpler and reference functions in libraries in other files.

Is there any harm in passing Ractive itself as an argument, so these "external" functions can access it?

For example, instead of:

oninit: function() {
    // tons of code here 
}

doing this?

oninit: function() {    
    doThisThing(ractive)
}

Then, in a separate file:

function doThisThing(ractive) {
    pingAnAPI(function(response) {
        ractive.set('data', response);
        )};
}

Just wondering if there would be memory issues or any other undesirable effect if you did this a lot.

Thanks, Ractive is awesome!

1

There are 1 answers

0
Joseph On

doThisThing appears to be your data layer, and should not be aware of your UI layer. Otherwise, you'd risk tightly coupled code.

Instead of breaking out the code and passing the ractive around, break away your data fetching logic. Call the API, have it return a promise. Ractive can hold on to that promise.

// On the component
oninit: function() {
  var instance = this;
  pingAnAPI().then(function(response){
    instance.set('data', response);
  });
}

// On your data layer
pingAnAPI: function(){
  return $.get('path/to/endpoint');
}

Another way you can do it, since you're considering separate files, is to break out from index.html and use component files. Read the component spec for authors page for more details.

As for memory issues, I'd not worry about that as early as now. Code maintainability should be your first agenda.