How to pass aguments to a viewModel function?


#1

My main-view-model.js has a main function with many viewModel functions inside, like this:

function createViewModel(db) {
var viewModel = new Observable();

viewModel.open = function(arg) {
if (arg === "something") {
dialog.alert("something");
}
}
viewModel.webSite = function() {
db.execSQL("INSERT INTO web_site (site, username, password) VALUES (?, ?)", [this.siteName, this.siteUser, this.sitePass]).then(id => {
console.log("INSERT RESULT", id);
}, error => {
console.log("INSERT ERROR", error);
});
}
}

I want the “open” function to be used by many buttons on my app but for this purpose I need an argument to tell the function what to do, for example:

<Button id="info" tap="{{ open }}" /> <!--I need the open function to know the request is coming from the info button-->

How can I do this?


#2

In angular NS I would move the shared functionality into a service and inject the service into all components that need it.

Looks like you’re using vanilla JS, though, which I haven’t spent a whole lot of time with. Someone correct me if I’m wrong here, but I’d probably still move the reusable code into a service class and instantiate that class from each view model that needs it.


#3

Thanks for your answer. Yes I’m using vanilla JS. This is how I solved the problem:

I changed viewModel.open = function(arg) { to exports.open = function (arg)

Then I imported the function in the appropriate JS file using:

var request = require("../../main-view-model");

Finally I created a function only to call the open function:

function redirect() {
request.open();
}

#4

The way this is typically done in {N} is simply by adding an attribute to the tag, such as:

request="info"

Then, in the handler code, you access that attribute to determine what you want to do; something like:

  var button = args.object;
  var request = button.request;  // "info"