How to access the view model instance, if I tap a button inside the listview


#1

I’ve added a couple of buttons, inside a ListView, and I’m having an issue with the binding.

<ListView row="1" items="{{ items }}" itemTap="{{ onListViewItemTap }}" class="menuListView" id="listView">
            <ListView.itemTemplate class="combo-list-item">
                <GridLayout columns="*, auto, auto" rows="30, auto" class="{{ listItemClass }}" >
                    <Label row="0" text="{{ displayName }}" textWrap="true" class="item-name" />
                    <Label row="1" text="{{ ingredients }}" textWrap="true" class="menu-ingredients"/>
                    
                    <StackLayout row="0" col="2" colSpan="2" rowSpan="2" orientation="horizontal" class="stepper-container-combo">
                          <Button text=" - " tap="{{ subtractQuantity }}"  class="stepper-button-combo"/>
                          <Label text="  0  " class="stepper-spacer"/>
                          <Button text=" + " tap="{{ $parents['ListView'].addQuantity }}"  class="stepper-button-combo"/>
                    </StackLayout>

                
                </GridLayout>
            </ListView.itemTemplate>
        </ListView>

After some research, I’ve added a tap event like this
tap="{{ $parents[‘ListView’].addQuantity }}"

and this nows get triggered, and in the addQuantity() function the “this” correspond to the “item” object, which is one of the elements of the items="{{ items }}" array that the list is binded to.

My question is: how do I access the viewModel instance from inside my addQuantity() function when the button is tapped, so that I can update the overall quantity and other elements that are outside the listview, and are binded to the viewModel instance.

Any ideas?

Thank you!


#2

Ok, coming back to answer my own question, I just figured out. For reference in the future, and to help others, you can get the instance of the viewModel by accessing the bindingContext property of the page property of the view.

basically,
first, make sure you import the View:
import { View } from ‘ui/core/view’;

Then, inside my addQuantity() method,

var view = <View>args.object;
var model = view.page.bindingContext;

model is now an instance of the viewModel, so I can access everything outside the listview item.

Thank you!


#3

Hi! I came across your topic, and I’m facing the same problem.

I tried the solution though I don’t get whats the <View> on
var view = <View>args.object;

is for.

please help